package com.pvdnc.worldmagisk.shell;

import android.util.Base64;
import android.util.Log;

import com.pvdnc.worldmagisk.shell.client.CommandResponse;
import com.pvdnc.worldmagisk.shell.server.CommandRequest;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class PacketDecoder extends ByteToMessageDecoder {
    private static final String TAG= PacketDecoder.class.getSimpleName();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int type=in.readInt();
        Log.d(TAG,"type:"+type);
        int cmdLength= in.readInt();
        Log.d(TAG,"cmdLength:"+cmdLength);
        byte[] data=new byte[cmdLength];
        in.readBytes(data);
        data= Base64.decode(data,Base64.DEFAULT);
        switch (type){
            case Packet.TYPE_REQUEST:{
                CommandRequest request =new CommandRequest(new String(data));
                out.add(request);
                break;
            }
            case Packet.TYPE_RESPONSE:{
                CommandResponse response=new CommandResponse();
                response.mResult=new String(data);
                out.add(response);
                break;
            }
        }
    }
}
